package com.kayeah82.application.avatar.qq.component;

import com.kayeah82.application.avatar.qq.model.Avatar;
import com.kayeah82.application.avatar.qq.utils.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.util.Collections;

/**
 * @author kayeah82
 */
@Component
public class QQAvatarUtils {

    private static final Logger logger = LoggerFactory.getLogger(QQAvatarUtils.class);

    private RestTemplate restTemplate;

    public QQAvatarUtils() {
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setBufferRequestBody(false);
        this.restTemplate = new RestTemplate(requestFactory);
    }

    private Avatar handle(String qq) {
        String url = String.format(QQ_AVATAR_API_V2, qq);
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Collections.singletonList(MediaType.APPLICATION_OCTET_STREAM));
        HttpEntity<String> entity = new HttpEntity<>(headers);
        ResponseEntity<byte[]> response = restTemplate.exchange(url, HttpMethod.GET, entity, byte[].class);
        if (response.getStatusCode() == HttpStatus.OK) {
            return new Avatar(response.getBody(), response.getHeaders().getContentType());
        } else {
            logger.error(response.getStatusCode().toString());
            throw new RuntimeException("get qq avatar error");
        }
    }

    @PostConstruct
    private void init() {
        instance = new QQAvatarUtils();
    }

    public static Avatar getAvatar(String qq) {
        Avatar avatar;
        try {
            avatar = getInstance().handle(qq);
        } catch (RuntimeException e1) {
            logger.error(e1.getMessage());
            try {
                File defaultAvatar = new ClassPathResource("/static/img/qq.png").getFile();
                avatar = new Avatar(IOUtils.io(defaultAvatar), MediaType.IMAGE_PNG);
            } catch (IOException e2) {
                logger.error("default avatar not found or occurred error in processing.", e2);
                throw new RuntimeException("load default avatar failed.");
            }
        }
        return avatar;
    }

    private static QQAvatarUtils getInstance() {
        if (instance == null) {
            logger.warn("QQAvatarUtils is not ready.");
            throw new NullPointerException();
        }
        return instance;
    }

    private static QQAvatarUtils instance;

    private final static String QQ_AVATAR_API_V1 = "https://thirdqq.qlogo.cn/g?b=qq&nk=%s&s=100";
    private final static String QQ_AVATAR_API_V2 = "http://thirdqq.qlogo.cn/headimg_dl?dst_uin=%s&spec=100";

}
